from flask import Blueprint, jsonify, request, json
import orgMgmt.orgOperation.subcomOprt as subcomOprt

subcom = Blueprint('subcom', __name__)


@subcom.route('/', methods=['GET'])
def index():
    subcomOprt.hello()
    print("here is subcom")
    return jsonify('subcommmm')


# ###########################################################################################################登录
@subcom.route('/init', methods=['GET'])
def init():
    if subcomOprt.getAllSubcom() == 0:
        return subcomOprt.getAllSubcom()
    else:
        subcomlist = []
        for line in subcomOprt.getAllSubcom():
            subcomlist.append({"subcom_id": line[0], "subcom_name": line[1],
                               "super_company_id": line[2], "super_company_name": line[3]})
        print(subcomlist)
    return jsonify(subcomlist)


@subcom.route('/newsub', methods=['POST'])
def newsub():
    print("new a subcompany")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if subcomOprt.newsub(json_data.get('subcom'), json_data.get('supercom')):
        return jsonify(1)
    else:
        return jsonify(2)


@subcom.route('/editsub', methods=['POST'])
def editsub():
    print("new a subcompany")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if subcomOprt.editsub(json_data.get('subid'), json_data.get('subcom'), json_data.get('supercom')):
        return jsonify(1)
    else:
        return jsonify(2)


@subcom.route('/select', methods=['POST'])
def subcomVagueSelect():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    word = json_data.get('word')
    subcomlist = []
    if subcomOprt.searchSubcom(word) == 0:
        return jsonify(0)
    else:
        for line in subcomOprt.searchSubcom(word):
            subcomlist.append({"subcom_id": line[0], "subcom_name": line[1],
                               "super_company_id": line[2], "super_company_name": line[3]})
    print(subcomlist)
    return jsonify(subcomlist)


@subcom.route('/delete', methods=['POST'])
def subcomDelete():
    data = request.get_data()
    print(data)
    word = data.decode("utf-8")
    print(word)

    if subcomOprt.deleteSubcom(word):
        return jsonify(1)
    else:
        return jsonify(2)


